
#include "UtilManager.h"
#include "GuiThread.h"

using namespace ttg_internal::utils;

//-------------------
//--- UtilManager ---
//-------------------

static UtilManager::UtilManager()
{
	//Creating collections.
	_utilities = gcnew List<UtilityPlusController ^>();
	_info = gcnew GlobalInfo();
}

System::String ^UtilManager::Register(IUtility ^utility)
{
	try
	{
		//Initing.
		UtilityPlusController ^upc = gcnew UtilityPlusController(utility);
		if (_utilities->Count == 0)
			GuiThread::CreateWindow();
		_utilities->Add(upc);
		GuiThread::GetForm()->SetActionMenu(upc);
		utility->Init(gcnew UtilityProps(utility->Name), upc->Controller, _info);
		return nullptr;
	}
	catch (System::Exception ^ex)
	{
		return System::String::Format("Exception has been thrown during initialization of \"{0}\":{1}",
									  utility->Name, ex->ToString());
	}
}

System::String ^UtilManager::Init(UtilityProps ^utility)
{
	try
	{
		//Loading.
		System::String ^error = nullptr;
		IUtility ^u = UtilLoader::LoadUtility(utility->Name, error);
		if (u == nullptr)
			return error;
		//Initing.
		u->Name = utility->Name;
		return UtilManager::Register(u);
	}
	catch (System::Exception ^ex)
	{
		return System::String::Format("Exception has been thrown during initialization of \"{0}\":{1}",
									  utility->Name, ex->ToString());
	}
}

void UtilManager::Close(System::String ^name)
{
	try
	{
		for each (UtilityPlusController ^upc in _utilities)
			if (upc->Utility->Name == name)
			{
				upc->Utility->Close();
				_utilities->Remove(upc);
				if (_utilities->Count == 0)
					GuiThread::DestroyWindow();
				return;
			}
	}
	catch (System::Exception ^ex)
	{
		System::Windows::Forms::MessageBox::Show(
							System::String::Format("Internal error: {0}.", ex->ToString()),
							"Internal error");
	}
}
